package com.Fate.filter;

import com.Fate.common.CodeMsg;
import com.Fate.common.Constant;
import com.Fate.common.Result;
import com.Fate.util.RespUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录页面
 */
@WebFilter(value = {"*.do","*.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;

        //获取session
        HttpSession session = req.getSession();
        //获取登录用户
        Object user = session.getAttribute(Constant.CURRENT_USER_KEY);
        //不为空 说明已经登录
        if (user!=null){
            //放行
            chain.doFilter(req,resp);
            return;
        }
        //获取登录资源
        String uri= req.getRequestURI();//获取请求的资源路径
        if(uri.endsWith("index.jsp") || uri.endsWith("checkCode.do")|| uri.endsWith("redirect.jsp")){
            //放行
            chain.doFilter(req,resp);
            return;
        }
        //是否是处理登录的请求
        String service = req.getParameter("service");
        //处理登录的请求
        if (uri.endsWith("user.do")&&"login".equals(service)){
            //放行
            chain.doFilter(req,resp);
            return;
        }

        //获取ajax请求标记
        //X-Requseted-With:XMLHttpRequest
        String flag = req.getHeader("X-Requested-With");
        //一致说明ajax请求
        if ("XMLHttpRequest".equalsIgnoreCase(flag)){
            //告诉前端 需要登录
            RespUtil.write(resp,new Result(CodeMsg.SYS_LOGIN_INVILD_ERROR));
            return;
        }

        //其他情况不放行
        resp.sendRedirect("redirect.jsp");
    }

    @Override
    public void destroy() {

    }
}

